package com.zy.composeworld.ktx

import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.View
import android.view.Window


private var View.lastClickTime: Long
    get() = if (getTag(id) != null) getTag(id) as Long else 0L
    set(value) {
        setTag(id, value)
    }

fun View.singleClick(
    changeSelect: Boolean = false,
    duration: Long = 300L,
    onClick: (View) -> Unit
) {
    setOnClickListener {
        val currentClickTime = System.currentTimeMillis()
        if (currentClickTime - lastClickTime > duration) {
            if (changeSelect){
                it.isSelected = !it.isSelected
            }
            onClick(it)
        }
        lastClickTime = currentClickTime
    }
}

fun View.saveToBitmap(window: Window?, onSave: (bitmap: Bitmap?) -> Unit) {
    if (window == null) return
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val location = IntArray(2)
    getLocationInWindow(location)
    PixelCopy.request(
        window,
        Rect(location[0], location[1], location[0] + width, location[1] + height),
        bitmap,
        {
            if (it == PixelCopy.SUCCESS) {
                onSave.invoke(bitmap)
            }
        },
        Handler(Looper.getMainLooper())
    )
}

fun View.saveToBitmap(window: Window?, array: List<Int>, onSave: (bitmap: Bitmap?) -> Unit) {
    if (window == null) return
    val bitmap = Bitmap.createBitmap(array[2], array[3], Bitmap.Config.ARGB_8888)
    PixelCopy.request(
        window,
        Rect(array[0], array[1], array[2], array[3]),
        bitmap,
        {
            if (it == PixelCopy.SUCCESS) {
                onSave.invoke(bitmap)
            }
        },
        Handler(Looper.getMainLooper())
    )
}